<template>
	<!-- 资产库 -->
	<div class="assetArchivePage">
		<!-- tag菜单组件 -->
		<IncomeTagMenu projectName="资产经营管理" menuName="资源库" />
		<div class="content">
			<div class="searchBox">
				<el-form :inline="true" :model="searchForm" class="demo-form-inline">
					<el-form-item label="">
						<el-select
							v-model="searchForm.selectedColumnArr"
							style="width: 135px"
							multiple
							collapse-tags
							collapse-tags-tooltip
							placeholder="全部"
							@change="columnShowChange"
						>
							<el-option
								v-for="item in state.columsOptions"
								:key="item.value"
								:label="item.label"
								:value="item.propName"
							>
							</el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="搜索">
						<el-input
							v-model="searchForm.searchVal"
							placeholder="根据资产名称搜索"
							maxlength="32"
							style="width: 150px"
              clearable
              @keyup.enter="doSearch"
						/>
					</el-form-item>
					<el-form-item label="资产位置">
						<el-select
							v-model="searchForm.areaTypeVal"
							style="width: 120px"
							placeholder="请选择区域"
							@change="areaTypeChange"
						>
							<el-option
								v-for="item in searchForm.areaTypeOptionsArr"
								:key="item.code"
								:label="item.name"
								:value="item.code"
							/>
						</el-select>
						<el-select
							v-model="searchForm.streerTypeVal"
							class="w-135 m-l10"
							placeholder="请选择街道"
						>
							<el-option
								v-for="item in searchForm.streerTypeOptionsArr"
								:key="item.code"
								:label="item.name"
								:value="item.code"
							/>
						</el-select>
					</el-form-item>
					<el-form-item label="资产类型">
						<el-select v-model="searchForm.assetsTypeVal" class="w-135">
							<el-option
								v-for="item in searchForm.assetsTypeOptionsArr"
								:key="item.value"
								:label="item.label"
								:value="item.value"
							/>
						</el-select>
					</el-form-item>
					<el-form-item label="取得方式">
						<el-select v-model="searchForm.sourceTypeVal" class="w-135">
							<el-option
								v-for="item in searchForm.sourceTypeOptionsArr"
								:key="item.value"
								:label="item.label"
								:value="item.value"
							/>
						</el-select>
					</el-form-item>
					<el-form-item>
						<el-button
							color="#FF7B50"
							style="color: #fff"
							type="primary"
							@click="doSearch"
							>查看</el-button
						>
						<el-button style="" color="#F0F0F0" @click="doReset"
							>重置</el-button
						>
						<el-divider direction="vertical" class="searchDivider" />
						<el-button
							plain
							color="#FF7B50"
							class="assetInputBtn"
							@click="addAsset"
						>
							<img
								class="addAssetBtnImg"
								src="@/assets/iconImg/daoru.png"
								alt=""
							/>
							资产录入</el-button
						>
					</el-form-item>
				</el-form>
			</div>
			<PublicStatistics
				:cardArr="cardInfo.cardArr"
				getWidth="332px"
			></PublicStatistics>
			<el-table
				ref="multipleTable"
				v-loading="tableLoadingFlag"
				:data="state.tableData"
				tooltip-effect="dark"
				style="width: 100%; margin-bottom: 23px"
				@selection-change="handleSelectionChange"
			>
				<el-table-column type="selection" width="40" />
				<el-table-column prop="index" label="序号" width="55" align="center" />
				<el-table-column
					v-for="(n, i) in state.showColumsArr"
					:key="i"
					:prop="n.propName"
					:label="n.label"
					:width="state.showColumsArr.length <= 7 ? '' : n.width"
					align="center"
				>
					<template #default="scope">
						<div v-if="n.propName == 'assetsPosition'">
							{{ scope.row.regionName }}{{ scope.row.streetName }}
						</div>
						<div v-if="n.propName == 'createTime'">
							{{ dayjs(scope.row.createTime).format("YYYY-MM-DD HH:mm:ss") }}
						</div>
						<div v-if="n.propName == 'type'">
							{{
								scope.row.type == 1
									? "农贸市场"
									: scope.row.type == 2
									? "商业(绿道)"
									: scope.row.type == 3
									? "商业(商铺)"
									: scope.row.type == 4
									? "写字楼"
									: scope.row.type == 5
									? "综合体"
									: "其他"
							}}
						</div>
						<div v-if="n.propName == 'sourceType'">
							{{
								scope.row.sourceType == 1
									? "政府划拨"
									: scope.row.sourceType == 2
									? "委托经营"
									: scope.row.sourceType == 3
									? "租借"
									: scope.row.sourceType == 4
									? "自建"
									: scope.row.sourceType == 5
									? "有偿转让"
									: "其他"
							}}
						</div>
					</template>
				</el-table-column>
				<!-- :width="
            state.showColumsArr.length > 6 && state.showColumsArr.length != 9
              ? ''
              : '260'
          " -->
        <el-table-column label="操作" width="260" align="center" fixed="right">
          <template #default="scope">
            <el-button
              color="#FF7B50"
              style="color: #fff"
              @click="goDetail(scope.row)"
              >详情</el-button
            >
            <el-button
              color="#93D6FF"
              style="color: #fff"
              @click="checkHousingDetail(scope.row.assetsId)"
              >房源明细</el-button
            >
            <el-button plain class="button_edit" @click="goEdit(scope.row)"
              >编辑</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-button
        class="f-l"
        color="#F12527"
        style="color: #fff; width: 76px; height: 40px"
        :disabled="state.deletBtnDisFlag"
        @click="deletAssets"
        >删除</el-button
      >
      <el-pagination
        v-model:page-size="defualtPageSize"
        :total="state.total"
        :page-sizes="[20, 30, 40, 50, 100, 150, 200]"
        layout="total, sizes, prev, pager, next, jumper"
        :current-page="state.currentPage"
        @current-change="pageChang"
        @size-change="sizeChange"
      />
    </div>
    <!-- 房源明细 -->
    <el-drawer
      v-model="drawerShowFlag"
      direction="rtl"
      size="50%"
      :show-close="false"
      :close-on-click-modal="false"
    >
      <template #header="{ close }">
        <div class="drawerTitleBox SourceHanSansMedium">房源明细清单</div>
        <img
          class="closeBtnBox"
          src="@/assets/iconImg/close.png"
          alt=""
          @click="close"
        />
      </template>
      <el-table :data="drawerState.drawerTableData">
        <el-table-column
          property="index"
          label="序号"
          width="55"
          align="center"
        />
        <el-table-column
          property="housingNumber"
          label="门牌号"
          align="center"
        />
        <el-table-column
          property="useType"
          label="房源用途"
          width="150"
          align="center"
        >
          <template #default="scope">
            {{
              scope.row.useType == 1
                ? '出租'
                : scope.row.useType == 2
                ? '自用'
                : scope.row.useType == 3
                ? '医疗'
                : scope.row.useType == 4
                ? '移交'
                : '委托运营'
            }}
          </template>
        </el-table-column>
        <el-table-column
          property="area"
          label="房源持有面积"
          width="200"
          align="center"
        />
        <el-table-column property="status" label="房源状态" align="center">
          <template #default="scope">
            {{
              scope.row.status == 1
                ? '在用'
                : scope.row.status == 0
                ? '闲置'
                : '停用'
            }}
          </template>
        </el-table-column>
      </el-table>
    </el-drawer>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref, watch, markRaw } from 'vue'
import { useRouter } from 'vue-router'
import {
  ElForm,
  ElFormItem,
  ElTable,
  ElTableColumn,
  ElSelect,
  ElOption,
  ElPagination,
  ElDrawer,
  ElDivider,
  ElMessage,
  ElMessageBox
} from 'element-plus'
import dayjs from 'dayjs'
import {
  jsonParseStringfy,
  sortCompare,
  numToFixed
} from '@/common/utils/GlobalUtils'
import {
  assetsTypeOptionsArr,
  assetsGetTypeOptionsArr
} from '@/common/dict/dictCollect'
import PublicStatistics from '@/components/PublicStatistics.vue'
import IncomeTagMenu from '@/components/IncomeTagMenu.vue'
import { assetsApi, housingApi } from '@/api/assets'
const router = useRouter()

const searchForm = reactive({
  selectedColumnArr: [], // 选中的要展示的列
  searchVal: null,
  areaTypeVal: null,
  areaTypeOptionsArr: [],
  streerTypeVal: null,
  streerTypeOptionsArr: [],
  assetsTypeVal: '',
  assetsTypeOptionsArr: [],
  sourceTypeVal: '',
  sourceTypeOptionsArr: []
})

// 取得方式选项转换
if (assetsGetTypeOptionsArr.length > 0) {
  let newArr = jsonParseStringfy(assetsGetTypeOptionsArr)
  newArr.unshift({ label: '全部', value: '' })
  searchForm.sourceTypeOptionsArr = newArr
}
// 资产类型选项转换
if (assetsTypeOptionsArr.length == 6) {
  let newArr = jsonParseStringfy(assetsTypeOptionsArr)
  newArr.unshift({ label: '全部', value: '' })
  searchForm.assetsTypeOptionsArr = newArr
}

// 初始化获取区域
const initAreaOptions = (type, cd) => {
  assetsApi.getLocations(type, cd).then((res) => {
    const { code, data, msg } = res
    if (code == 200) {
      if (cd) {
        searchForm.streerTypeOptionsArr = data
      } else {
        searchForm.areaTypeOptionsArr = data
      }
    }
  })
}
const areaTypeChange = (val) => {
  initAreaOptions(2, val)
}

const doSearch = () => {
  initAmountData()
  initTableData()
}

const doReset = () => {
  searchForm.searchVal = null
  searchForm.areaTypeVal = null
  searchForm.streerTypeVal = null
  searchForm.assetsTypeVal = ''
  searchForm.sourceTypeVal = ''
  initTableData()
}

const addAsset = () => {
  router.push({ path: '/asset/company/assetAdd/pageType=add'})
}

const cardInfo = reactive({
  cardArr: [
    {
      title: '资产总数',
      num: '--',
      url: require('@/assets/iconImg/zichanzs.png'),
      unit: '个'
    },
    {
      title: '房源总数',
      num: '--',
      url: require('@/assets/iconImg/fangyuanzs.png'),
      unit: '个'
    },
    {
      title: '总建筑面积',
      num: '--',
      url: require('@/assets/iconImg/jianzhumj.png'),
      unit: '㎡'
    }
    // { // 3.30暂时屏蔽
    //   title: "资产可用面积",
    //   num: "--",
    //   url: require("@/assets/iconImg/keyongmj.png"),
    //   unit: "㎡",
    // },
  ]
})
// 初始获取资产总数
const initAmountData = () => {
  assetsApi.getAssetsStatistics().then((res) => {
    const { code, data } = res
    if (code == 200) {
      if (data.assetsTotalNum) {
        cardInfo.cardArr[0].num = numToFixed(data.assetsTotalNum).split('&')[0]
        cardInfo.cardArr[0].unit = numToFixed(data.assetsTotalNum).split('&')[1]
          ? numToFixed(data.assetsTotalNum).split('&')[1] + '个'
          : cardInfo.cardArr[0].unit
      }
      if (data.housingTotalNum) {
        cardInfo.cardArr[1].num = numToFixed(data.housingTotalNum).split('&')[0]
        cardInfo.cardArr[1].unit = numToFixed(data.housingTotalNum).split(
          '&'
        )[1]
          ? numToFixed(data.housingTotalNum).split('&')[1] + '个'
          : cardInfo.cardArr[1].unit
      }
      if (data.totalBuildArea) {
        cardInfo.cardArr[2].num = numToFixed(data.totalBuildArea, 2).split(
          '&'
        )[0]
        cardInfo.cardArr[2].unit = numToFixed(data.totalBuildArea, 2).split(
          '&'
        )[1]
          ? numToFixed(data.totalBuildArea, 2).split('&')[1] + '㎡'
          : cardInfo.cardArr[2].unit
      }
      // 3.30暂时屏蔽
      // if (data.totalUsableArea) {
      //   cardInfo.cardArr[3].num = numToFixed(data.totalUsableArea, 2).split(
      //     "&"
      //   )[0];
      //   cardInfo.cardArr[3].unit = numToFixed(data.totalUsableArea, 2).split(
      //     "&"
      //   )[1]
      //     ? numToFixed(data.totalUsableArea, 2).split("&")[1] + "㎡"
      //     : cardInfo.cardArr[3].unit;
      // }
    }
  })
}

// table相关
const defualtPageSize = ref(50)
const tableLoadingFlag = ref(false)
const state = reactive({
  deletBtnDisFlag: true,
  columsOptions: [
    {
      value: 0,
      label: '资产名称',
      propName: 'assetsName',
      width: 180
    },
    {
      value: 1,
      label: '资产位置',
      propName: 'assetsPosition',
      width: 200
    },
    {
      value: 2,
      label: '资产类型',
      propName: 'type',
      width: 140
    },
    {
      value: 3,
      label: '取得方式',
      propName: 'sourceType',
      width: 150
    },
    {
      value: 4,
      label: '建筑面积',
      propName: 'buildArea',
      width: 100
    },
    // { // 3.30暂时隐藏
    //   value: 5,
    //   label: "可用面积",
    //   propName: "usableArea",
    //   width: 100,
    // },
    {
      value: 6,
      label: '房源数',
      propName: 'housingNum',
      width: 80
    },
    {
      value: 7,
      label: '责任部门',
      propName: 'departmentName',
      width: 130
    },
    {
      value: 8,
      label: '建档时间',
      propName: 'createTime',
      width: 170
    }
  ],
  showColumsArr: [],
  tableData: [],
  total: 1, // 总条数
  currentPage: 1 // 当前页
})

// 初始获取table数据
const initTableData = () => {
  tableLoadingFlag.value = true
  const params = {
    pageNum: state.currentPage,
    pageSize: defualtPageSize.value,
    param: {
      assetsName: searchForm.searchVal,
      regionCode: searchForm.areaTypeVal,
      streetCode: searchForm.streerTypeVal,
      assetsType: searchForm.assetsTypeVal,
      sourceType: searchForm.sourceTypeVal
    }
  }
  assetsApi.getAssetsPage(params).then((res) => {
    const { code, data, msg } = res
    if (code == 200) {
      state.tableData = data.content.map((n, i) => {
        n.index = i + 1
        return n
      })
      state.total = data.totalSize
      tableLoadingFlag.value = false
    } else {
      tableLoadingFlag.value = false
    }
  })
}

// 初始化设置table默认选中列为全部选项
searchForm.selectedColumnArr = state.columsOptions.map((n, i) => {
  return n.propName
})
state.showColumsArr = state.columsOptions
// table列的显示控制
const columnShowChange = (val) => {
  let newArr = []
  if (val.length > 0) {
    val.map((n, i) => {
      state.columsOptions.map((m, j) => {
        if (m.propName == n) {
          newArr.push(m)
        }
      })
    })
    // 按value值进行排序
    newArr.sort(sortCompare('value'))
    state.showColumsArr = newArr
  }
  if (val.length == 0) {
    state.showColumsArr = []
  }
}
// 分页
const pageChang = (val) => {
  state.currentPage = val
  initTableData()
}
const sizeChange = (val) => {
  defualtPageSize.value = val
  initTableData()
}

// table的复选
let selectedColumnsArr = ref([])
// watch( //使用ref定义未初始化的数组，监听时不能用.value且必须是深度监听。这种写法不仅可以监听数组本身的变化，也可以监听数组元素的变化。
//   selectedColumnsArr,
//   (newValue) => {
//     console.log('选择数组变化了', jsonParseStringfy(newValue))
//     selectedColumnsArr.value = jsonParseStringfy(newValue)
//   },
//   {deep: true}
// )
const handleSelectionChange = (val) => {
  console.log('选了几个？？？？', jsonParseStringfy(val))
  selectedColumnsArr.value = jsonParseStringfy(val)
  selectedColumnsArr.value.length
    ? (state.deletBtnDisFlag = false)
    : (state.deletBtnDisFlag = true)
}

const iconUrl = require('@/assets/iconImg/warning.png')
const deletAssets = () => {
  let idArrs = []
  selectedColumnsArr.value.map((n, i) => {
    idArrs.push(n.assetsId)
  })
  // 确认弹窗
  ElMessageBox.confirm(
    "<img style='width:20px;height:20px;margin-right: 5px;' src=" +
      iconUrl +
      ' />是否确认删除所选档案，数据删除后不可恢复!',
    '档案删除确认',
    {
      customClass: 'deletConfirmBox',
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      dangerouslyUseHTMLString: true,
      center: true,
      closeOnClickModal: false
    }
  )
    .then(() => {
      assetsApi.assetsDelete({assetsIds:idArrs}).then((res) => {
        const { code, data, msg } = res
        if (code === '200') {
          ElMessage({
            type: "success",
            message: "删除成功",
          });
          initAmountData();
          initTableData();
        }
      })
    })
    .catch(() => {})
}

// 详情
const goDetail = (row) => {
  router.push({
    path: '/asset/company/assetDetail/' + row.assetsId
  })
}
// 查看房源明细
const checkHousingDetail = (id) => {
  housingApi.getHousingList(id).then((res) => {
    const { code, data, msg } = res
    if (code == 200) {
      drawerState.drawerTableData = data.map((n, i) => {
        n.index = i + 1
        return n
      })
    }
  })
  drawerShowFlag.value = true
}
// 编辑
const goEdit = (row) => {
	router.push({ path: `/asset/company/assetEdit/pageType=edit&id=${row.assetsId}`})
}

// 抽屉相关
const drawerShowFlag = ref(false)
const drawerState = reactive({
  drawerTableData: []
})
// 初始化房源明细table
const initDrawerTabel = () => {}

onMounted(() => {
  initAreaOptions(1)
  initAmountData()
  initTableData()
})
</script>

<style lang="scss" scoped>
.assetArchivePage {
  .content {
    .w-135 {
      width: 135px;
    }
    .searchBox {
      margin-bottom: 28px;
      .el-form {
        .el-form-item {
          margin-bottom: 10px;
        }
        .assetInputBtn {
          &:hover {
            background-color: #fff;
            color: $btn-defualt-tx-color;
          }
          .addAssetBtnImg {
            width: 18px;
            height: 18px;
          }
        }
      }
      .searchDivider {
        height: 40px;
        margin: 0 30px;
      }
    }
  }
  .drawerTitleBox {
    font-size: 16px;
    font-weight: 500;
    color: #1a1a1a;
    text-align: center;
  }
  .closeBtnBox {
    width: 24px;
    height: 24px;
    cursor: pointer;
  }
}
</style>
<style lang="scss" scoped>
.assetArchivePage {
  :deep(.el-table) {
    .el-table__body {
      .cell {
        .el-button {
          width: 68px;
          height: 31px;
        }
      }
    }
  }
}
</style>
